import { Component, OnInit } from '@angular/core';
import {ActivatedRoute, Router} from "@angular/router";
import {ShelfService} from "../shelf.service";
import {StorageService} from "../../services/storage.service";
import {ConfirmationService} from "primeng/api";
import {MessageService} from "primeng/components/common/messageservice";
import {FormBuilder, Validators} from "@angular/forms";
import {BasePage} from "../../base.page";
import {onlytimeValidator} from "../../validator/validators";
import {EventBusService} from "../../services/event-bus.service";
import {PUblicMethod} from "../../services/PUblicMethod";

@Component({
  selector: 'app-update-applicaton',
  templateUrl: './update-applicaton.component.html',
  styleUrls: ['./update-applicaton.component.scss']
})
export class UpdateApplicatonComponent extends BasePage implements OnInit {
  shelfForm;
  fb: FormBuilder = new FormBuilder();
  beginTime;
  endTime;
  zh;
  cols;
  submitData;
  initStartTime: Date;
  showAddEquement : boolean = false;
  showAddMask: boolean = false;
  displayLocation: boolean = false;
  editdataSource = [];
  personalData = [];
  displayPersonel: boolean = false;
  brand: string;
  totalRecords;
  selectConstructions = [];
  statusNames;
  radioButton = [];
  viewState;
  tableDatas;
  updatedropDownData;
  assetshelve_type;
  location = [];
  treeModel;
  nowDate;
  assets;
  sid;
  detailData =[];
  shelflocation;
  devices;
  type;
  state = 'add';
  tempAsset;
  showViewDetailMask: boolean = false;
  approveGroup;
  constructor(
    private route: ActivatedRoute,
    private router:Router,
    private shelfService:ShelfService,
    private storageService: StorageService,
    public confirmationService: ConfirmationService,
    public   messageService:MessageService,
    private eventBusService:EventBusService
  ) {
    super(confirmationService,messageService)
  }

  ngOnInit() {
    this.treeModel={
      oid:""
    }
    this.nowDate = new Date();
    this.radioButton = [
      {label:'一级供电',value:'一级供电'},
      {label:'二级供电',value:'二级供电'},
      {label:'三级供电',value:'三级供电'}
    ];
    this.shelfForm = this.fb.group({
      'sid': [''],//上架单号
      'status':[''],//状态
      'creator': ['',Validators.required], //申请人
      'creator_org':[''], //申请人组织
      'creator_pid':[''], //申请人组织
      'assetshelve_type':[''],//上架类型
      'org_approver':[''], //审批人名称
      "usage_time": [''], //预计使用周期
      "assetshelve_location":[''], //计划上架区域
      "preoccupied_sid":[''],//关联预占单号
      "power_level":[''], //供应电极
      "assetshelve_reason":[''], //上架原因
      timeGroup:this.fb.group({
        startTime: ['', Validators.required],
        endTime: ['', Validators.required],
      },{validator:onlytimeValidator}),
    });
    this.beginTime = new Date();
    this.endTime = new Date();
    this.initStartTime = new Date();
    this.zh =new PUblicMethod().initZh();
    this.statusNames = [
      {label:'新建',value:'新建'},
    ];
    this.assetshelve_type = [
      {label:'自有上架',value:'自有上架'},
      {label:'托管上架',value:'托管上架'},
      {label:'故障替换',value:'故障替换'},
    ];
    this.cols = [
      {field: 'name', header: '设备名称'},
      {field: 'system', header: '设备分类'},
      {field: 'modle', header: '设备型号'},
      {field: 'power_jack_position1', header: 'PDU口编号'},
      {field: 'size', header: '高度(U)'},
    ];
    this.queryDetail();
    // this.queryJurList('');
  }
  viewOption(currentAsset){
    this.tempAsset= currentAsset;
    this.showViewDetailMask = !this.showViewDetailMask
  }
  closeViewDetail(bool){
    this.showViewDetailMask = bool;
  }
  queryDetail(){
    this.route.queryParams.subscribe(parms=>{
      if(parms['sid']){
        this.sid =parms['sid'];
      }
      this.detailData['sid'] = this.sid;
      this.shelfService.addDetail(this.sid).subscribe(data=>{
        this.detailData = data;

        this.shelflocation = this.detailData['assetshelve_location'];
        let locatios = [];
        for (let i in this.shelflocation){
          locatios.push(this.shelflocation[i].label)
        }
        for(let  i = 0 ;i<this.detailData['devices'].length;i++){
          let temp = this.detailData['devices'][i];
          temp['timeGroup'] = temp['room']+'>'+temp['cabinet']+'>'+temp['location'];
        }
        this.detailData['assetshelve_location'] = locatios
        this.editdataSource = this.detailData['devices']
        this.treeModel.oid = this.detailData['applicant_org_oid'];
        this.queryJurList('');
        if(!this.editdataSource){
          this.editdataSource = [];
          this.totalRecords = 0;
        }
        this.totalRecords = this.editdataSource.length;
        this.devices = this.editdataSource.slice(0,10);
      })
    });
  }
  updateOption(currentAsset,state,index){
    this.state =state;
    this.tempAsset= currentAsset;
    console.log(this.tempAsset)
    this.storageService.setCurrentShelf('shelfindex',index);
    this.showAddMask = true;
  }
  updateShelf(storage){
    let index = this.storageService.getCurrentShelf('shelfindex');
    if(this.viewState ==='update'){
      this.editdataSource[index] = storage;
      this.devices =storage;
      this.devices = this.editdataSource.slice(0,10);
      this.showAddMask = false;
    }
    this.editdataSource[index] = storage;
    this.devices = this.editdataSource.slice(0,10);
    for(let  i = 0 ;i<this.devices.length;i++){
      let temp = this.devices[i];
      temp['timeGroup'] = temp['room']+'>'+temp['cabinet']+'>'+temp['location'];
      console.log( temp['timeGroup'] )
    }
    this.showAddMask = false;
  }
  //添加
  showAdd(type){
    this.showAddMask = !this.showAddMask;
  }
  removeMask(bool){
    this.showAddMask = bool;
  }
  showLocationMask(){
    this.displayLocation = !this.displayLocation;
  }
  closeAddLocationMask(bool){
    this.displayLocation = bool;
  }
  addDevice(asset){
    this.editdataSource = [];
    this.editdataSource.push(asset);
    this.totalRecords = this.editdataSource.length;
    this.devices = this.editdataSource.slice(0,10);
    this.alert('添加成功')
  }
  addConstructionOrg(org){
    this.location = org;
    this.detailData['assetshelve_location'] = [];
    for(let i = 0;i<org.length;i++){
      this.detailData['assetshelve_location'].push(org[i]['label'])
    }
    this.detailData['assetshelve_location'] =  this.detailData['assetshelve_location'].join('>');
    this.displayLocation = false;
  }
  goBack() {
    let sid =  this.detailData['sid'];
    this.detailData['status_code'] = "";
    this.eventBusService.updateshelf.next(this.detailData['status_code']);
    this.router.navigate(['../shelfoverview'],{queryParams:{sid:'',state:'',title:'上架总览'},relativeTo:this.route})
  }

  displayEmitter(event) {
    this.displayPersonel = event;
  }
  dataEmitter(event) {
    this.displayPersonel = false;
    this.detailData['applicant']  = event.name;
    this.detailData['applicant_org']  = event.organization;
    this.detailData['applicant_org_oid']  = event.oid;
    // console.log(this.detailData['applicant_org_oid'])
    this.treeModel.oid =  this.detailData['applicant_org_oid'];
    this.queryJurList('');
  }
  //查询人员表格数据
  queryJurList(oid){
    this.shelfService.getPersonList(this.treeModel.oid).subscribe(data => {
      this.tableDatas = data;
      this.updatedropDownData = this.shelfService.DropdownData(this.tableDatas);
      this.detailData['approve'] = this.updatedropDownData[0]['value']['name'];
      this.detailData['approve_pid'] = this.updatedropDownData[0]['value']['pid'];
    })
  }
  showPersonMask(){
    this.displayPersonel = !this.displayPersonel;
  }
  clearTreeDialog () {
    this.detailData['applicant'] = '';
    this.detailData['applicant_org'] = '';
    this.updatedropDownData ='';
  }
  clearLocationDialog () {
    this.detailData['assetshelve_location'] = '';
  }
  showAddEquementMask(){
    this.showAddEquement = !this.showAddEquement;
  }
  closeAddEquementMask(bool){
    this.showAddEquement = bool;
  }
  addDev(metail){
    this.showAddEquement = false;
    for(let i = 0;i<metail.length;i++){
      this.editdataSource.push(metail[i]);
    }

    this.totalRecords = this.editdataSource.length;
    this.devices = this.editdataSource.slice(0,10);
  }
  loadCarsLazy(event) {
    setTimeout(() => {
      if(this.editdataSource) {
        this.devices = this.editdataSource.slice(event.first, (event.first + event.rows));
      }
    }, 0);
  }
  filterApprove = data => {
    if(typeof data === 'object') {
      this.detailData['approve'] = data['name'];
      this.detailData['approve_pid'] =  data['pid'];
    }
  }
  // 提交
  updateShelfSubmint(detailData,editdataSource){
    this.filterApprove(this.detailData['approve']);
    detailData.devices = editdataSource;
    detailData.assetshelve_location = this.location;
    this.shelfService.updateSubmit(detailData).subscribe(()=>{
      this.router.navigate(['../shelfoverview'],{queryParams:{title:'上架总览'},relativeTo:this.route})
    },(err:Error)=>{
      let message ;
      if(JSON.parse(JSON.stringify(err)).status===504){
        message = '似乎网络出现了问题，稍后重试'
      }else{
        message =err
      }
      this.confirmationService.confirm({
        message: message,
        rejectVisible:false,
      })
    })
  };
  // 保存
  saveShelfSubmint(detailData,editdataSource){
    this.filterApprove(detailData['approve']);
    detailData.devices = editdataSource;
    detailData.assetshelve_location = this.location;
    this.shelfService.updateSave(detailData).subscribe(()=>{
      this.router.navigate(['../shelfoverview'],{queryParams:{title:'上架总览'},relativeTo:this.route})
    },(err:Error)=>{
      let message ;
      if(JSON.parse(JSON.stringify(err)).status===504){
        message = '似乎网络出现了问题，稍后重试'
      }else{
        message =err
      }
      this.confirmationService.confirm({
        message: message,
        rejectVisible:false,
      })
    })
  };
  formSave(){
    this.saveShelfSubmint(this.detailData,this.editdataSource)
  }
  formSubmit(){
    this.updateShelfSubmint(this.detailData,this.editdataSource);
  }
  deleteStorage(){
    for(let i = 0;i<this.selectConstructions.length;i++){
      for(let j = 0;j<this.editdataSource.length;j++){
        if(this.selectConstructions[i]['ano']===this.editdataSource[j]['ano']){
          this.editdataSource.splice(j,1);
          this.devices = this.editdataSource.slice(0,10);
          this.selectConstructions = [];
        }
      }
    }
  }
}
